#!/bin/sh -e

prog="${0##*/}"
y=true

cleanup () {
  if test "$1" -ge 10 ; then
    rc-service -i -s utmp-init stop
  fi
  if test "$1" -ge 9 ; then
    rc-service -i -s btmpd stop
  fi
  if test "$1" -ge 8 ; then
    rc-service -i -s wtmpd stop
  fi
  if test "$1" -ge 7 ; then
    rc-service -i -s utmpd stop
  fi
  if test "$1" -ge 6 ; then
    rc-service -i -s utmp-prepare stop
  fi
  if test "$1" -ge 5 ; then
    rc-update delete utmp-init boot || :
  fi
  if test "$1" -ge 4 ; then
    rc-update delete btmpd boot || :
  fi
  if test "$1" -ge 3 ; then
    rc-update delete wtmpd boot || :
  fi
  if test "$1" -ge 2 ; then
    rc-update delete utmpd boot || :
  fi
  if test "$1" -ge 1 ; then
    rc-update delete utmp-prepare boot || :
  fi
}

while getopts 'yn' opt ; do
  case "$opt" in
    y) y=true ;;
    n) y=false ;;
    ?) echo "$prog: usage: $prog [ -y | -n ]" 1>&2 ; exit 100 ;;
  esac
  shift
done

if $y ; then
  rc-update add utmp-prepare boot || { cleanup 0 ; exit 1 ; }
  rc-update add utmpd boot || { cleanup 1 ; exit 1 ; }
  rc-update add wtmpd boot || { cleanup 2 ; exit 1 ; }
  rc-update add btmpd boot || { cleanup 3 ; exit 1 ; }
  rc-update add utmp-init boot || { cleanup 4 ; exit 1 ; }
  rc-service utmp-prepare start || { cleanup 5 ; exit 1 ; }
  rc-service utmpd start || { cleanup 6 ; exit 1 ; }
  rc-service wtmpd start || { cleanup 7 ; exit 1 ; }
  rc-service btmpd start || { cleanup 8 ; exit 1 ; }
  # We don't run utmp-init because it's not boot time.
  # : rc-service utmp-init start || { cleanup 9 ; exit 1 ; }
  echo "$prog: utmps services are now enabled. Use $prog -n to disable them." 1>&2
  echo "$prog: note that user accounting may not be accurate until the next reboot." 1>&2
else
  cleanup 10
  echo "$prog: utmps services are disabled. Use $prog -y to reenable them." 1>&2
fi
